import { Injectable, Logger, OnApplicationBootstrap } from '@nestjs/common';
import { lastValueFrom, catchError } from 'rxjs';
import { AxiosRequestConfig, AxiosError } from 'axios';
import { BusinessException } from '~/common/exceptions/business.exception';
import { HttpService } from '@nestjs/axios';

@Injectable()
export class HttpRequestService {
  private logger: Logger = new Logger('HttpRequest');
  constructor(private readonly httpService: HttpService) {}

  // 封装通用请求方法（支持是否携带 token）
  private async request<T>(
    config: AxiosRequestConfig,
  ): Promise<{ code: number; data?: T; message?: string }> {
    try {
      const response = await lastValueFrom(
        this.httpService
          .request({
            ...config,
          })
          .pipe(
            catchError((error: AxiosError) => {
              this.logger.error('请求失败，地址：' + config.url);
              throw new BusinessException(`接口请求失败`);
            }),
          ),
      );

      return {
        code: 200,
        data: response.data.data,
      };
    } catch (error) {
      return {
        code: error.response?.status || 500,
        message: error.message,
      };
    }
  }

  // GET 请求封装
  async get<T>(
    url: string,
    params?: Record<string, any>,
  ): Promise<{ code: number; data?: T; message?: string }> {
    return this.request<T>({
      method: 'GET',
      url,
      params,
    });
  }

  // POST 请求封装
  async post<T>(
    url: string,
    body: Record<string, any>,
    headers: Record<string, string> = {},
  ): Promise<{ code: number; data?: T; message?: string }> {
    return this.request<T>({
      method: 'POST',
      url,
      data: body,
      headers,
    });
  }
}
